package com.framework.common.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author lihanbo
 */
@Component
@Log4j2
public class RSAUtils {

    public String pubKey;
    public String priKey;

    @PostConstruct
    public void loadData() {
        try {
            pubKey = ResourceUtil.readUtf8Str("RSA/pub.key")
                    .replaceAll("-----BEGIN PUBLIC KEY-----", "")
                    .replaceAll("-----END PUBLIC KEY-----", "")
                    .replaceAll("\n", "");
            priKey = ResourceUtil.readUtf8Str("RSA/pri.key")
                    .replaceAll("-----BEGIN PRIVATE KEY-----", "")
                    .replaceAll("-----END PRIVATE KEY-----", "")
                    .replaceAll("\n", "");
        } catch (Exception ex) {
        }
    }

    /**
     * 公钥加密
     */
    public String encrypt(String publicKey, String data) {
        byte[] encrypt = SecureUtil.rsa(null, publicKey).encrypt(StrUtil.bytes(data, CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey);
        return Base64.encode(encrypt);
    }

    /**
     * 私钥解密
     */
    public String decrypt(String privateKey, String data) {
        byte[] decode = Base64.decode(data);
        byte[] decrypt = SecureUtil.rsa(privateKey, null).decrypt(decode, KeyType.PrivateKey);
        return StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8);
    }

}
